<?php
class Controller_Chong extends Controller_Template
{
    private $user = null;

    function __construct($req, $res)
    {
        $this->template = 'smarty:chong/index';
        parent::__construct($req, $res);

        $this->user    = new Chong_User();
    }

    public function action_index()
    {                             
        $this->echo_user_info();
        $this->template->set_filename('smarty:chong/index');
    }

    // 登录
    public function action_login()
    {
        $post = $this->request->post();
        if (! empty($post))
        {
            $passport = Arr::get($post, 'passport');
            $password = Arr::get($post, 'password');
			$checkcode = Arr::get($post, 'checkcode');
            $img = new securimage();
			$valid = $img->check(strtolower($checkcode));
			if ($valid !== TRUE){
				return $this->_err('登录失败，验证码错误', '/index');
			}
            $user = YYHAccount::login($passport, $password);
            if($user)
            {  
                $this->user->login($user['user_name'], $user['avatar_url'], $user['last_login_time'], $user['nick_name']);
                return $this->_suc('登录成功', '/index');
            }
            else
            {
                return $this->_err('登录失败，账户或密码错误', '/index');
            }
        }
    }
    public function action_openlogin($type) {
        $url = PcOpenLogin::instance($type)->get_login_url();
        if (empty($url)) {
            $this->_err('系统发请错误，请稍后再试', '/');
        } else {
            $this->request->redirect($url);
        }
    }

    //登录回调
    public function action_callback($type) {
        if (!PcOpenLogin::check_state()) {
            $this->_err('非法请求', '/');
        }
        $access_token = PcOpenLogin::instance($type,'pcopenlogin')->get_access_token();
        if (empty($access_token)) {
            $this->_err('获取授权出错', '/');
        }
        $openid = PcOpenLogin::instance()->get_openid($access_token);        
        if (empty($openid)) {
            $this->_err('获取用户出错', '/');
        }        
        if($type == 'qq') {
            $userinfo = YYHAccount::get_user_info_by_qq_openid($openid);            
        } else if($type == 'sina') {
           $userinfo = YYHAccount::get_user_info_by_sinaweibo_uid($openid);
        }        
        if( !empty($userinfo) ) {
            $this->user->login($userinfo['user_name'], $userinfo['avatar_url'], $userinfo['last_login_time'], $userinfo['nick_name']);
            return $this->_suc('登录成功', '/income');
        } else {            
            return $this->_err('您的账号尚未登陆过应用汇', '/');
        }
        exit();
    }
    // 退出
    public function action_logout()
    {
        $this->user->logout();
        $this->request->redirect('/');
    }

    //充值记录
    public function action_income_list($page = 1)
    {
        $username = $this->user->username();
        if (empty($username))
        {
            return $this->_err('用户还未登录', '/');
        }
        $this->echo_user_info();
        $pagesize   = 15;
        $totalnum   = IAppPay_LiangXiang::income_total($username);
        $totalpage  = ceil($totalnum / $pagesize);
        $start      = max($page - 1, 0) * $pagesize;
        $list       = IAppPay_LiangXiang::income_list($username, $start, $pagesize);    
                    
        $this->template->set('list', $list);        
        $this->template->set('type', 'income');
        $this->template->set('username', $username);
        $this->template->set('totalpage', $totalpage);
        $this->template->set('page', $page);
        $this->template->set('paytypes', Kohana::config('iapppay.paytype'));
        $this->template->set('balance', $this->user->balance());
        $this->template->set_filename('smarty:chong/tradelist');
    }

    //消费记录
    public function action_payment_list($page = 1)
    {
        $username = $this->user->username();
        if (empty($username))
        {
            return $this->_err('用户还未绑定', '/');
        }
        $this->echo_user_info();
        $pagesize = 15;
        $totalnum   = IAppPay_LiangXiang::payment_total($username);
        $totalpage  = ceil($totalnum / $pagesize);
        $start      = max($page - 1, 0) * $pagesize;
        $list       = IAppPay_LiangXiang::payment_list($username, $start, $pagesize);
        
        $this->template->set('list', $list);
        $this->template->set('type', 'payment');        
        $this->template->set('totalpage', $totalpage);
        $this->template->set('page', $page);
        $this->template->set('paytypes', Kohana::config('iapppay.paytype'));
        $this->template->set('balance', $this->user->balance());
        $this->template->set_filename('smarty:chong/tradelist');
    }
    
    public function action_customer_service(){
        $this->echo_user_info();
        $this->template->set_filename('smarty:chong/customer_service');
    }

    //充值创建订单
    public function action_create_order()
    {
        $post       = $this->request->post();
        $num        = intval(Arr::get($post, 'num', 0));
        $paytype    = Arr::get($post, 'paytype');
        if ($num <= 0)
        {
            return $this->_err('不是有效的数量', '/income');
        }

        $username = $this->user->username();
        if (empty($username))
        {
            return $this->_err('用户还未登录，请登录后再试', '/');
        }

        $pay = Paysdk::instance($paytype);
        if (empty($pay))
        {
            return $this->_err('不支持的支付方式', '/');
        }

        $amount = round($num/10, 2);
        list($order_id, ) = Weixin_Income::create_order($username, $num*10, $paytype);


        $parameter = array(
        "out_trade_no"	=> $order_id,
        "total_fee"	=> $amount,//元
        "body"	=> '应用豆'.$num.'个',
        );

        $form = $pay->set_info($parameter)->get_form("继续支付");
        $this->template->set_filename('smarty:chong/creat_order');
        $this->template->set('form', $form);
    }

    //充值页面
    public function action_income()
    {
        $username = $this->user->username();
        $this->echo_user_info();        
        if (empty($username))
        {
            return $this->_err('用户还未登录', '/');
        }
        $this->template->set('username', $this->user->username());
        $this->template->set('balance', $this->user->balance());
        $this->template->set_filename('smarty:chong/income');
    }

    //支付通知
    public function action_notify($paytype = '')
    {
        if (empty($paytype))
        {
            exit;
        }
        kohana::$log->add('DEBUG', '_notify_'.json_encode($_GET).'|'.json_encode($_POST));
        $pay = Paysdk::instance($paytype);
        $data = $pay->verify_notify();
        if (!$data)
        {
            exit('fail');
        }
        $status = Weixin_Income::get_order_status($data['out_trade_no']);
        if($status || Weixin_Income::pay_order($data['out_trade_no'], $data['transaction_id'], date('Y-m-d H:i:s'), 2))
        {
            exit('success');
        }
        exit('fail');
    }

    //支付返回调用
    public function action_return($paytype = '')
    {
        if (empty($paytype))
        {
            exit;
        }
        $pay = Paysdk::instance($paytype);
        $data = $pay->verify_return();
        if (!$data)
        {
            return $this->_err('充值失败', '/income');
        }
        $status = Weixin_Income::get_order_status($data['out_trade_no']);
        if($status || Weixin_Income::pay_order($data['out_trade_no'], $data['transaction_id'], date('Y-m-d H:i:s')))
        {
            return $this->_suc('充值成功', '/income_list');
        }
        return $this->_err('充值失败', '/income');
    }

    public function before()
    {
        parent::before();
        if( $this->user->is_login() ) {            
           $this->template->set('is_login','ture');               
        } else {
            $this->template->set('is_login','false');
        }
        $this->template->set('_version', $this->_vesion);
        $this->template->set('action', $this->request->action());
    }

    private function echo_user_info() {        
        $this->template->set('nickname',$this->user->get_user_nick_name()?$this->user->get_user_nick_name():$this->user->username()); 
        $this->template->set('avatar',$this->user->get_user_avatar());
        $this->template->set('last_login_time',$this->user->get_last_login_time());
        $this->template->set('balance', $this->user->balance());
    }

    private function _suc($data, $url = '')
    {
        $arr['data']    = $data;
        $arr['status']  = 1;
        $arr['msg']     = '';
        $arr['url']     = $url;
        if ($this->request->is_ajax())
        {
            exit(json_encode($arr));
        }
        else
        {
            $arr['msg'] = $data;
            $this->template->set('type', 'success');
            $this->template->set('info', $arr);
            $this->template->set_filename('smarty:chong/message');
        }
    }

    private function _err($msg, $url = '')
    {
        $arr['data']    = array();
        $arr['status']  = 0;
        $arr['msg']     = $msg;
        $arr['url']     = $url;
        if ($this->request->is_ajax())
        {
            exit(json_encode($arr));
        }
        else
        {
            $this->template->set('type', 'error');
            $this->template->set('info', $arr);
            $this->template->set_filename('smarty:chong/message');
        }
    }
}

